// pages/firework/add/index.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js"), formatTime = require("../../../utils/formatTime.js"),
common_Js = require("../../../component/common.js");
import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
var context = null;// 使用 wx.createContext 获取绘图上下文 context
var isButtonDown = false;//是否在绘制中
var arrx = [];//动作横坐标
var arry = [];//动作纵坐标
var arrz = [];//总做状态，标识按下到抬起的一个组合
var canvasw = 0;//画布宽度
var canvash = 0;//画布高度
Page({

    /**
     * 页面的初始数据
     */
    data: {
        companyId:0,
        workerList:[],
        safeUserList:[],
        outWorkerList:[],
        measures:[],
        recordType:1,
        company:{},
        nowDate:'',
        submitState:false,
        isShowPop:false,
        isShowPopMin:false,
        isShowPopMax:false,
        showZeRenList:false,
        sysUserList:[],
        userActions:[],
        userNames:[],
        beginTime:'00:00',
        endTime:'23:59',
        currentDate: new Date().getTime(),
        minDate: new Date(2018, 0, 1).getTime(),
        currentTimeMin:'00:00',
        currentTimeMax:'23:59',
        isShowPopupAddWorker:false,
        currentTime:new Date(),
        workerResult: [],//选择的动火人
        editWorker:{workerName:'', workType:'', workCardNum:'', isOut:1,},
        fireWork:{
            recordType: 1,//作业证的类型 0 - 动火作业证  1 - 密闭作业证  2 - 高空作业证
            recordNo:'', //作业证编号
            regCompanyId:0, //申请动火单位id          
            regCompanyName:'', //申请动火单位名称        
            workCompanyId:0,//动火单位id       
            workCompanyName:'',//动火单位名称
            regUserName:'',//申请人
            opLevel:1,//动火作业级别
            fireBeginTime:'',//申请动火开始时间
            fireEndTime:'',//申请动火结束时间
            workType:'',//工种
            otherSpecialWork:'',//涉及其他的特殊作业
            headerSysUserId:0,
            recordHeaderUser:'',//责任人
            fireAddress:'',//动火地址
            state:0,//状态
            workHeight:'4米'
        },
        useHour:'1小时',//作业时长
        hourColumns: ['1小时', '2小时', '3小时', '4小时', '5小时', '6小时', '7小时', '8小时'],
        signImg:'',
        isShowPopWorkHeight:false,
        workHeightTxt:'4米',
        workHeightColums:[],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.type){
            this.data.recordType = parseInt(options.type);
            this.data.fireWork.recordType = parseInt(options.type);
        }
        
    	var ss = common_Js.formatTimeSimple(new Date());
        var date = new Date();
        //年 getFullYear()：四位数字返回年份
        var year = date.getFullYear(); //getFullYear()代替getYear()
        //月 getMonth()：0 ~ 11
        var month = date.getMonth() + 1;
        //日 getDate()：(1 ~ 31)
        var day = date.getDate();
        //时 getHours()：(0 ~ 23)
        var hour = date.getHours();
        //分 getMinutes()： (0 ~ 59)
        var minute = date.getMinutes();
        //秒 getSeconds()：(0 ~ 59)
        var second = date.getSeconds();

        var minHour = 0;
        if(hour == 0){
        	minHour = 0;
        }else{
        	minHour = hour - 1;
        }
        var maxHour = hour;

        // var hourBeginStr = minHour < 10 ? '0' + minHour : minHour;
        // hourBeginStr += ':00'; 
        var hourBeginStr = hour < 10 ? '0' + hour.toString() + ':' + (minute < 10 ? '0' + minute.toString() : minute.toString()) : hour.toString() + ':'
         + (minute < 10 ? '0' + minute.toString() : minute.toString());
         maxHour = hour + 1;
        // var hourEndStr = maxHour < 10 ? '0' + maxHour : maxHour;
        var hourEndStr = maxHour < 10 ? '0' + maxHour.toString() + ':' + (minute < 10 ? '0' + minute.toString() : minute.toString()) : maxHour.toString() + ':'
         + (minute < 10 ? '0' + minute.toString() : minute.toString());
        // hourEndStr += ':00';

        this.data.beginTime = hourBeginStr;
        this.data.endTime = hourEndStr;


        this.data.fireWork.fireBeginTime = ss + ' ' + this.data.beginTime +':00';
        this.data.fireWork.fireEndTime = ss + ' ' + this.data.endTime+ ':00';

        this.data.nowDate = ss;

        this.data.currentTime = formatTime.dateStrChangeTime(this.data.nowDate + ' ' + this.data.beginTime +':00')
        
        console.log('this.data.fireWork.fireEndTime',this.data.fireWork.fireEndTime)

        this.setData({
          nowDate: ss,
          beginTime: hourBeginStr,
          endTime: hourEndStr,
        })
        this.startCanvas();
        this.onHttpInit()
    },

  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    console.log('onHttpInit')
    var that = this;
    fetchApi.httpPost('/fire/work/view', {
      record_type: that.data.recordType
    }, function (res) {
      console.log("添加申请信息", res)
      if (res.data.code == 0) {
          var company = res.data.data.shop;
          that.data.fireWork.regCompanyId = company.id;
          that.data.fireWork.regCompanyName = company.shopName;
          that.data.fireWork.workCompanyId = company.id;
          that.data.fireWork.workCompanyName = company.shopName;
          that.data.sysUserList = res.data.data.sysUserList;
          that.data.safeUserList = res.data.data.safeUserList;
          that.data.fireWork.regUserName = res.data.data.sysUser.name;
          that.setData({
            sysUser: res.data.data.sysUser,
            workerList: res.data.data.workUsers,
            measures:res.data.data.measures,
            company: res.data.data.shop,
            userActions:res.data.data.userActions,
            userNames: res.data.data.userNames,
            sysUserList: res.data.data.sysUserList,
            safeUserList: res.data.data.safeUserList,
          })
          if(res.data.data.workHeightMin > 0){
            var min = res.data.data.workHeightMin;
            var max = res.data.data.workHeightMax;
            that.data.workHeightColums = [];
            for(let i = min;i<=max;i++){
              that.data.workHeightColums.push(i+'米');
            }
          }
          that.setData({
            workHeightColums: that.data.workHeightColums
          })
      } 
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
  
  onShowHeaderUser() {
    this.setData({ showZeRenList: true });
  },
  onCloseHeaderUser() {
    this.setData({ showZeRenList: false });
  },
  onSelectHeaderUser(event) {
    console.log('onSelectHeaderUser',event.detail);

    var index = event.detail.index;
    var sysUserId = this.data.sysUserList[index].userId;
    var name = this.data.sysUserList[index].name;
    this.data.fireWork.headerSysUserId = sysUserId;
    this.data.fireWork.recordHeaderUser = name;
    this.setData({
        fireWork: this.data.fireWork
    })
    this.onCloseHeaderUser();

  },
  onChangeWorker(e){
      console.log('onChangeWorker',e.detail)
      this.setData({
        workerResult: e.detail
      })
  },
  bindInput(e){
      var key = e.currentTarget.dataset.key;
      if(key == 'edit_worker_name'){
        this.data.editWorker.workerName = e.detail;
      } else if(key == 'edit_worker_type'){
        this.data.editWorker.workType = e.detail;
      } else if(key == 'edit_worker_num'){
        this.data.editWorker.workCardNum = e.detail;
      }
      else if(key == 'record_no'){
        this.data.fireWork.recordNo = e.detail;
      }
      else if(key == 'work_type'){
        this.data.fireWork.workType = e.detail;
      }
      else if(key == 'other_special_work'){
        this.data.fireWork.otherSpecialWork = e.detail;
      }
      else if(key == 'reg_company_name'){
        this.data.fireWork.regCompanyName = e.detail;
      }else if(key == 'fire_company_name'){
        this.data.fireWork.workCompanyName = e.detail;
      }else if(key == 'reg_user_name'){
        this.data.fireWork.regUserName = e.detail;
      }else if(key == 'address'){
        this.data.fireWork.fireAddress = e.detail;
      }else if(key == 'fire_date'){
        this.data.fireWork.regUserName = e.detail;
      }else if(key == 'header_man'){
        this.data.fireWork.recordHeaderUser = e.detail;
      }else if(key == 'work_height'){
        this.data.fireWork.workHeight = e.detail;
      }else if(key == 'work_content'){
        this.data.fireWork.workContent = e.detail;
      }
  },
  submitOp(){
  
    var fireWork = this.data.fireWork;    

    if(fireWork.regCompanyName == ''){
      Toast('请输入申请单位');return ;
    }

    if(fireWork.regUserName == ''){
      Toast('请输入申请人');return ;
    }
    if(this.data.workerResult.length == 0 && this.data.outWorkerList.length == 0){
      Toast('请选择或添加作业人');return ;
    }
    
    if(this.data.signImg == ''){
      Toast('请进行电子签名');return ;
    }


    this.onHttpSubmit();
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpSubmit: function (e) {
    var that = this;
    fetchApi.httpPost('/fire/work/add/record', {
      data_json:that.data.fireWork,
      worker_result: that.data.workerResult,
      out_worker: that.data.outWorkerList,
      sign_img: that.data.signImg
    }, function (res) {
      console.log("发起申请响应数据", res)
      if (res.data.code == 0) {
          Toast.success(res.data.msg);
          
          setTimeout(function(){
            wx.navigateBack({
                delta: -1
            })
        },500)
      }else{
        Toast.fail(res.data.msg);
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
  onClickAddWorker(){
      this.setData({
        isShowPopupAddWorker: !this.data.isShowPopupAddWorker
      })
  },
  submitAddWorker(){
    if(this.data.editWorker.workerName == ''){
      Toast('请输入作业人姓名');return ;
    } else if(this.data.editWorker.workType == ''){
      Toast('请输入作业工种');return ;
    }
    //  else if(this.data.editWorker.workCardNum == ''){
    //   Toast('请输入作业证件号');return ;
    // }

    this.data.outWorkerList.push(this.data.editWorker)
    this.setData({
      outWorkerList:this.data.outWorkerList
    })

    this.data.editWorker = {workerName:'', workType:'', workCardNum:'',isOut:1},

    this.setData({
      editWorker:this.data.editWorker
    })

    this.onClickAddWorker()
  },
  onConfirmDate(event){
    console.log('onConfirmDate',event);
    this.setData({ isShowPop: false });
    var date = common_Js.formatTimeTwo(event.detail,'Y-M-D')
    console.log('date',date)
    this.data.nowDate = date;
  },
  onConfirmHour(e){
    console.log('onConfirmHour',e)
    var type = e.currentTarget.dataset.htype;
    var time = e.detail;
    if(type == 'min'){
      this.data.beginTime = time;
      this.setData({
        beginTime:time
      })
      this.onClickDateMin();      
      this.data.fireWork.fireBeginTime = this.data.nowDate + ' ' + this.data.beginTime+ ':00';
    }else{
      this.data.endTime = time;
      this.setData({
        endTime:time
      })
      this.data.fireWork.fireEndTime = this.data.nowDate + ' ' + this.data.endTime + ':59';
      this.onClickDateMax()
    }
    var beginTime = formatTime.dateStrChangeTime(this.data.fireWork.fireBeginTime);
    console.log('beginTime',beginTime);
    this.data.currentTime = beginTime;
  },
  onConfirmWorkHour(e){
    console.log('onConfirmWorkHour',e);
    var index = e.detail.index;

    var beginTime = formatTime.dateStrChangeTime(this.data.fireWork.fireBeginTime);
    console.log('beginTime',beginTime);
    this.data.currentTime = beginTime;
    
    var endTime = beginTime.setHours(beginTime.getHours() + (index + 1));
    var time = formatTime.formatTime(endTime);
    console.log('endTime', time);
    this.data.fireWork.fireEndTime = time;

    var hour = e.detail.value;
    this.setData({
        useHour:hour,
        isShowPopMax:false,
    })
  },
  onCancleHour(){
    this.setData({
        isShowPopMin: false
    })
  },
  onChangeFireLevel(e){
    console.log('onChangeFireLevel',e);
    this.data.fireWork.opLevel = e.detail;
  },
  onClickDate(){
    this.setData({
      isShowPop : !this.data.isShowPop
    })
  },
  onClickDateMin(){
    this.setData({
      isShowPopMin : !this.data.isShowPopMin
    })
  },
  onClickDateMax(){
    this.setData({
     isShowPopMax : !this.data.isShowPopMax
    })
  },
  getResult(time, type) {
    const date = new Date(time);
    switch (type) {
      case 'datetime':
        return date.toLocaleString();
      case 'date':
        return date.toLocaleDateString();
      case 'year-month':
        return `${date.getFullYear()}/${date.getMonth() + 1}`;
      case 'time':
        return time;
      default:
        return '';
    }
  },
  formatData(type, value) {
    if (type === 'year') {
      return `${value}年`;
    }
    if (type === 'month') {
      return `${value}月`;
    }
    return value;
  },
  touchHandler: function (e) { //当月用电触摸显示
   yuelineChart.showToolTip(e, { //showToolTip图表中展示数据详细内容
    background: '#7cb5ec',
    format: function (item, category) {
     return category + '日 ' + item.name + ':' + item.data
    }
   });
  },
  onChangeSafe(e){
    console.log('onChangeSafe',e.detail)
    this.data.fireWork.safeSysUserId = e.detail;
    this.setData({
      fireWork: this.data.fireWork
    })
  },
  onClickWorkHeight(){
    this.setData({
      isShowPopWorkHeight : !this.data.isShowPopWorkHeight
    })
  },
  onConfirmWorkHeight(e){   
    console.log('onConfirmWorkHeight', e)
    this.data.fireWork.workHeight = e.detail.value;
    this.data.workHeightTxt = e.detail.value
    this.setData({
      workHeightTxt: e.detail.value
    })
    this.onClickWorkHeight();
  },
 /**
  * 以下 - 手写签名 / 上传签名
  */
 startCanvas: function () {//画布初始化执行
  var that = this;
  //获取系统信息
  wx.getSystemInfo({
  success: function (res) {
    canvasw = res.windowWidth;
    canvash = res.windowHeight;
    that.setData({ canvasw: canvasw });
    that.setData({ canvash: canvash });
  }
  }); 
  this.initCanvas();
  this.cleardraw(); 
},
//初始化函数
initCanvas: function () {
  context = wx.createCanvasContext('canvas');
  context.beginPath()
  context.fillStyle = 'rgba(255, 255, 255, 0)';
  context.setStrokeStyle('#000000');
  context.setLineWidth(4);
  context.setLineCap('round');
  context.setLineJoin('round');
},
canvasStart: function (event) {
  isButtonDown = true;
  arrz.push(0);
  arrx.push(event.changedTouches[0].x);
  arry.push(event.changedTouches[0].y);
},
canvasMove: function (event) {
  if (isButtonDown) {
    arrz.push(1);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
  }
  for (var i = 0; i < arrx.length; i++) {
    if (arrz[i] == 0) {
      context.moveTo(arrx[i], arry[i])
    } else {
      context.lineTo(arrx[i], arry[i])
    }
  }
  context.clearRect(0, 0, canvasw, canvash);
  context.setStrokeStyle('#000000');
  context.setLineWidth(4);
  context.setLineCap('round');
  context.setLineJoin('round');
  context.stroke();
  context.draw(false);
},
canvasEnd: function (event) {
  isButtonDown = false;
},
//清除画布
cleardraw: function () {
  arrx = [];
  arry = [];
  arrz = [];
  context.clearRect(0, 0, canvasw, canvash);
  context.draw(true);
},
  uploadSignImg(mer_id){
      var that = this
      //生成图片
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        //设置输出图片的宽高
        // destWidth:150, 
        // destHeight:150,
        // fileType:'jpg',
        quality:1.0,
        success: function (res) {
          console.log(res)
          // canvas图片地址 res.tempFilePath
          that.data.signImg = res.tempFilePath;
          wx.uploadFile({
            url: fetchApi.getPlatformUrl() + '/fire/work/uploadSign',
            filePath: res.tempFilePath,
            name: 'file',
            formData: {
              user_id: that.data.user_id,
            },
            success: function (res) {
              console.log('uploadFile success res', res);
              var dataJson = JSON.parse(res.data);
              if(dataJson.code == 0){
                that.data.signImg = dataJson.data.file_name;
                Toast("已上传成功，请处理下一步");
              }
              console.log('that.data.signImg',that.data.signImg)
            },
            fail: function (res) {
              console.log('uploadFile fail res', res)
            }
          })

        },
        fail: function () {
          wx.showModal({
            title: '提示',
            content: 'canvas生成图片失败。微信当前版本不支持，请更新到最新版本！',
            showCancel: false
          });
        },
        complete: function () {}
      })
  },
  onClickAddWorker(){
    this.setData({
      isShowPopupAddWorker: !this.data.isShowPopupAddWorker
    })
  },
  submitAddWorker(){
  if(this.data.editWorker.workerName == ''){
    Toast('请输入作业人姓名');return ;
  } else if(this.data.editWorker.workType == ''){
    Toast('请输入作业工种');return ;
  }
  //  else if(this.data.editWorker.workCardNum == ''){
  //   Toast('请输入作业证件号');return ;
  // }

  this.data.outWorkerList.push(this.data.editWorker)
  this.setData({
    outWorkerList:this.data.outWorkerList
  })

  this.data.editWorker = {workerName:'', workType:'', workCardNum:'',isOut:1},

  this.setData({
    editWorker:this.data.editWorker
  })

  this.onClickAddWorker()
  },
  onChangeWorkerIsOut(e){
  console.log('onChangeWorkerIsOut', e)
  this.data.editWorker.isOut = parseInt(e.detail);
  },
})